<template>
  <div id="searchView">
    <div class="main">
      <input-search />
      <goods-info-cart :data="goodsList" />
      <div v-if="goodsList.length === 0">
        <el-empty :image-size="100" description="搜索结果为空" />
        <like-goods-view v-if="showLike" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import InputSearch from "@/components/InputSearch.vue";
import GoodsInfoCart from "@/components/GoodsInfoCart.vue";
import { useRoute } from "vue-router";
import { onMounted, onUnmounted, ref, watch } from "vue";
import { GoodsControllerService, GoodsEsDto } from "@/api";
import LikeGoodsView from "@/components/LikeGoodsView.vue";
//获取路由
const route = useRoute();
//获取路由参数
const search = ref<string>();

const goodsList = ref<GoodsEsDto[]>([]);
const showLike = ref(false);

function getGoodsSearchResult() {
  if (stopFlag.value) return;
  //请求数据
  GoodsControllerService.getListWithEsUsingGet(
    pageNum.value,
    10,
    undefined,
    undefined,
    undefined,
    search.value
  ).then((res) => {
    if (res.data.length < 11) {
      stopFlag.value = true;
    }
    goodsList.value.push(...res.data);
    if (goodsList.value.length === 0) {
      showLike.value = true;
    }
  });
}

const pageNum = ref(1);
// 结束标识
const stopFlag = ref(false);
const timeout = ref();
const handleScroll = () => {
  if (
    document.documentElement.scrollTop +
      document.documentElement.clientHeight >=
    document.documentElement.scrollHeight
  ) {
    if (!timeout.value) {
      timeout.value = setTimeout(() => {
        pageNum.value = pageNum.value + 1;
        timeout.value = null;
      }, 1000);
    }
  }
};
watch(
  () => route.query.keyword,
  () => {
    search.value = route.query.keyword as string;
    goodsList.value = [];
    pageNum.value = 1;
    stopFlag.value = false;
    showLike.value = false;
    getGoodsSearchResult();
  },
  { immediate: true }
);
watch(
  () => pageNum.value,
  () => {
    getGoodsSearchResult();
  }
);

onMounted(() => {
  document.addEventListener("scroll", handleScroll, true);
});
onUnmounted(() => {
  document.removeEventListener("scroll", handleScroll, true);
});
</script>

<style lang="scss" scoped>
#searchView {
  overflow-y: auto;

  .main {
    position: absolute;
    width: 80%;
    margin-top: 86px;
  }
}
</style>
